<template>
    <div class="workable-workableResult-container">
        <el-card shadow="hover" class="mb10" v-auth="'workable:result:list'">
			<el-input size="small" v-model="search.traceId" placeholder="请输入追踪标识" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
            <el-date-picker size="small" type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="ml10"></el-date-picker>
            <el-button size="small" icon="el-icon-search" type="primary" class="ml10" @click="onTableSearch()">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'workable:result:remove'" size="small" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableWorkableResultRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
				<el-table-column label="追踪标识" prop="traceId" show-overflow-tooltip>
					<template #default="scope">
						<el-button size="mini" type="text" @click="onCopyTraceId(scope.row)">复制</el-button>
						<span class="ml10">{{scope.row.traceId}}</span>
					</template>
				</el-table-column>
				<el-table-column label="任务名称" prop="taskName" show-overflow-tooltip></el-table-column>
				<el-table-column label="节点名称" prop="nodeName" show-overflow-tooltip></el-table-column>
				<el-table-column label="状态" prop="status" show-overflow-tooltip width="80">
					<template #default="scope">
						<span v-if="scope.row.status" class="color-primary">正常</span>
						<span v-else class="color-danger">异常</span>
					</template>
				</el-table-column>
				<el-table-column label="消息内容" prop="message" show-overflow-tooltip></el-table-column>
                <el-table-column label="执行时间" prop="createTime" show-overflow-tooltip width="180"></el-table-column>
                <el-table-column label="操作" show-overflow-tooltip width="125">
                    <template #default="scope">
						<el-button size="mini" type="text" @click="onOpenDesignWorkableTask(scope.row)">详情</el-button>
                        <el-button size="mini" type="text" @click="onOpenDetailWorkableResult(scope.row)">数据</el-button>
                        <el-button v-auth="'workable:result:remove'" size="mini" type="text" @click="onTabelRowDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                background
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
		<DetailWorkableResult ref="detailWorkableResultRef"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import DetailWorkableResult from '/@/views/workable/result/detailWorkableResult.vue';
import { getWorkableResultList, delWorkableResult } from '/@/api/workable/result/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { copyText } from '/@/utils/commonFunction';
import { useRouter } from 'vue-router';
export default {
    name: 'workable/result',
    components: { DetailWorkableResult },
	props: {
		taskId: {
			type: String,
			default: () => '',
		},
		runmode: {
			type: Number,
			default: () => 1,
		}
	},
    setup(props) {
		const router = useRouter();
        const tableWorkableResultRef = ref();
        const detailWorkableResultRef = ref();
        const state = reactive({
            search:{
				traceId: '',
				taskId: props.taskId,
				runmode: props.runmode,
                startTime: '',
                endTime: '',
                pageNum: 1,
                pageSize: 10,
				orderBy: 'createTime',
				isAsc: 'desc'
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            getWorkableResultList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableWorkableResultRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
			state.search.traceId = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的节点执行结果信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delWorkableResult(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条节点执行结果信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delWorkableResult([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData();
                    }
                });
            }).catch(() => {});
        };
		// 打开详情弹窗
		const onOpenDetailWorkableResult = (row: object) => {
			detailWorkableResultRef.value.openDialog(row);
		};
		const onCopyTraceId = (row: object) => {
			copyText(row.traceId);
		}
		// 打开工作流设计器
		const onOpenDesignWorkableTask = (row: object) =>{
			row = row || state.tableData.selections[0];
			router.push({
				path: '/workable/editor',
				query: { id : row.taskId, traceId: row.traceId, t: new Date().getTime() }
			});
		}
        // 页面加载时
        onMounted(() => {
            loadTableData();
        });
		//监听model数据
		watch(() => [props.taskId, props.runmode], () => {
			state.search.taskId = props.taskId;
			state.search.runmode = props.runmode;
			loadTableData(state.search);
		}, {deep: true});
		
        return {
            tableWorkableResultRef,
            detailWorkableResultRef,
            onTableSearch,
            onResetSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onTabelRowsDel,
            onTabelRowDel,
			onOpenDetailWorkableResult,
			onCopyTraceId,
			onOpenDesignWorkableTask,
            ...toRefs(state),
        };
    },
};
</script>